import Router from 'koa-router'
import mq from '../mysql'
import { getTime, createToken } from '../utils'

const router = new Router()

router.post(
  '/getToken',
  async (ctx, next) => {
    const { nickName, contact = '123456' } = ctx.request.body
    const names = await mq(`
      SELECT * FROM user WHERE name = '${nickName}'
    `)
    if (names.length !== 0) {
      ctx.params.body = {
        status: false,
        msg: '该昵称已被占用',
      }
      next()
    } else {
      const token = createToken(nickName, contact)
      await mq(
        `INSERT INTO user (name,contact,userStatus,creationTime,token) VALUES ('${nickName}','${contact}',0,'${getTime()}','${token}')`
      )
      ctx.params.body = {
        status: true,
        data: { token },
      }
      next()
    }
  },
  (ctx) => {
    ctx.body = ctx.params.body
  }
)
export default router
